/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import control.UserManager;
import java.awt.Button;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.User;

/**
 *
 * @author My PC
 */
public class PanelUser extends javax.swing.JPanel {

    /**
     * Creates new form PanelUser
     */
    DefaultTableModel dtbm = new DefaultTableModel();
    boolean Insert;
    boolean Edit;
    ButtonGroup bg = new ButtonGroup();

    public PanelUser() {
        initComponents();
        bg.add(jadmin);
        bg.add(juser);
// hiển thị dữ liệu ra bảng
        dtbm.addColumn("Tài Khoản");
        dtbm.addColumn("Họ Tên");
        dtbm.addColumn("Điện Thoại");
        dtbm.addColumn("Địa Chỉ");
        dtbm.addColumn("Admin");
        reset();
        loadTable();
        SetTextFeild(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jtxtUser = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jtxtName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jtxtPhone = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jPass = new javax.swing.JPasswordField();
        jadmin = new javax.swing.JRadioButton();
        juser = new javax.swing.JRadioButton();
        jTextField1 = new javax.swing.JTextField();
        jbSave = new javax.swing.JButton();
        jbEdit = new javax.swing.JButton();
        jbInsert = new javax.swing.JButton();
        jbCancel = new javax.swing.JButton();
        jbDelete = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.blue), "Detail User", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 2, 18))); // NOI18N

        jLabel1.setText("UserName");

        jLabel2.setText("Password");

        jLabel4.setText("Full Name");

        jLabel3.setText("Phone");

        jLabel5.setText("Address");

        jLabel6.setText("Admin");

        jadmin.setText("TRUE");
        jadmin.setEnabled(false);
        jadmin.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jadminMouseClicked(evt);
            }
        });

        juser.setText("FALSE");
        juser.setEnabled(false);
        juser.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                juserMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jtxtUser)
                    .addComponent(jtxtName)
                    .addComponent(jPass, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE))
                .addGap(74, 74, 74)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addGap(18, 18, 18)
                        .addComponent(jadmin)
                        .addGap(35, 35, 35)
                        .addComponent(juser))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(jtxtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField1)))
                .addContainerGap(71, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(jtxtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5)
                    .addComponent(jPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jtxtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jadmin)
                        .addComponent(juser)))
                .addGap(21, 21, 21))
        );

        jbSave.setText("SAVE");
        jbSave.setEnabled(false);
        jbSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSaveActionPerformed(evt);
            }
        });

        jbEdit.setText("EDIT");
        jbEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbEditActionPerformed(evt);
            }
        });

        jbInsert.setText("ADD_NEW");
        jbInsert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbInsertActionPerformed(evt);
            }
        });

        jbCancel.setText("CANCEL");
        jbCancel.setEnabled(false);
        jbCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbCancelActionPerformed(evt);
            }
        });

        jbDelete.setText("DELETE");
        jbDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbDeleteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 602, Short.MAX_VALUE))
                .addGap(28, 28, 28))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(139, 139, 139)
                        .addComponent(jbInsert)
                        .addGap(69, 69, 69)
                        .addComponent(jbEdit)
                        .addGap(47, 47, 47)
                        .addComponent(jbDelete))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(214, 214, 214)
                        .addComponent(jbSave)
                        .addGap(47, 47, 47)
                        .addComponent(jbCancel)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbEdit)
                    .addComponent(jbInsert)
                    .addComponent(jbDelete))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbCancel)
                    .addComponent(jbSave))
                .addContainerGap(43, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
//Sử lý sự kiện click chuột vào Table
    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        //lấy ra giá trị của Row được chọn
        int index = jTable1.getSelectedRow();
        // chuyển dữ liệu từ DefaultTableModel thành Vector
        Vector Row = (Vector) dtbm.getDataVector().get(index);
        //Lấy giá trị ở vị trí 0 ở đây là username có thể lấy như ID do vị trí sác định
        String username = Row.get(0).toString();
        //lấy ra giá trị được trọn trong SQL
        User item = UserManager.GetUserByUsername(username);
        LoadDetailUser(item);
    }//GEN-LAST:event_jTable1MouseClicked

    private void jbInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbInsertActionPerformed
        jbEdit.setEnabled(false);
        jbDelete.setEnabled(false);
        SetSaveCancelButton();
        SetTextFeild(true);
        SetTextFeildNull();
        Insert = true;

    }//GEN-LAST:event_jbInsertActionPerformed

    private void jbCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelActionPerformed
        jbEdit.setEnabled(true);
        jbDelete.setEnabled(true);
        jbInsert.setEnabled(true);
        SetTextFeildNull();
        SetTextFeild(false);
        jbSave.setEnabled(false);
        jbCancel.setEnabled(false);
    }//GEN-LAST:event_jbCancelActionPerformed

    private void jbSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSaveActionPerformed
        if (Insert == true) {
            InsertButton();
            reset();
            loadTable();
        }
        if (Edit == true) {
            EditButton();
            reset();
            loadTable();
        }

    }//GEN-LAST:event_jbSaveActionPerformed

    private void jbEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbEditActionPerformed
        // TODO add your handling code here:
        jbInsert.setEnabled(false);
        jbDelete.setEnabled(false);
        SetSaveCancelButton();
        SetTextFeild(true);
        jtxtUser.setEditable(true);
        Edit = true;

    }//GEN-LAST:event_jbEditActionPerformed

    private void jbDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbDeleteActionPerformed
       

        int confirm = JOptionPane.showConfirmDialog(this, "Would you like to Delete USER " +jtxtUser.getText()+ "?", "Warning", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
                UserManager.DeleteUser(jtxtUser.getText());
                reset();
                loadTable();
            } 
    }//GEN-LAST:event_jbDeleteActionPerformed

    private void jadminMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jadminMouseClicked
        jadmin.setSelected(true);
        juser.setSelected(false);
    }//GEN-LAST:event_jadminMouseClicked

    private void juserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_juserMouseClicked
         jadmin.setSelected(false);
        juser.setSelected(true);
    }//GEN-LAST:event_juserMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField jPass;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JRadioButton jadmin;
    private javax.swing.JButton jbCancel;
    private javax.swing.JButton jbDelete;
    private javax.swing.JButton jbEdit;
    private javax.swing.JButton jbInsert;
    private javax.swing.JButton jbSave;
    private javax.swing.JTextField jtxtName;
    private javax.swing.JTextField jtxtPhone;
    private javax.swing.JTextField jtxtUser;
    private javax.swing.JRadioButton juser;
    // End of variables declaration//GEN-END:variables

    private void loadTable() {
        List<User> list = UserManager.SelectAllUsers();
       

        for (User item : list) {
            Vector v = new Vector();
            v.add(item.getUSERNAME());
            v.add(item.getENAME());
            v.add(item.getPHONE());
            v.add(item.getADDRESS());
            v.add(item.isADMIN());
            dtbm.addRow(v);
        }
        jTable1.setModel(dtbm);
    }

    private void LoadDetailUser(User user) {
        jtxtUser.setText(user.getUSERNAME());
        jPass.setText(user.getPASSWORD());
        jtxtPhone.setText(user.getPHONE());
        jTextField1.setText(user.getADDRESS());
        jtxtName.setText(user.getENAME());
        if (user.isADMIN()) {
            jadmin.setSelected(true);
            juser.setSelected(false);
        } else {
            juser.setSelected(true);
            jadmin.setSelected(false);
        }
    }

//    private void SetTextFeild(boolean temp) {
//        if (temp == true) {
//            jtxtName.setEnabled(true);
//            jPass.setEnabled(true);
//            jtxtPhone.setEnabled(true);
//            jtxtUser.setEnabled(true);
//            jTextField1.setEnabled(true);
//            jadmin.setEnabled(true);
//            juser.setEnabled(true);
//        } else {
//            jtxtName.setEnabled(false);
//            jPass.setEnabled(false);
//            jtxtPhone.setEnabled(false);
//            jtxtUser.setEnabled(false);
//            jTextField1.setEnabled(false);
//            jadmin.setEnabled(false);
//            juser.setEnabled(false);
//        }
//
//    }
    
        private void SetTextFeild(boolean temp) {
            jtxtName.setEditable(temp);
            jPass.setEditable(temp);
            jtxtPhone.setEditable(temp);
            jtxtUser.setEditable(temp);
            jTextField1.setEditable(temp);
            jadmin.setEnabled(temp);
            juser.setEnabled(temp);
        }
    private void SetTextFeildNull() {
        jtxtName.setText("");
        jPass.setText("");
        jtxtPhone.setText("");
        jtxtUser.setText("");
        jTextField1.setText("");
        juser.setSelected(true);
    }

    private void SetSaveCancelButton() {
        jbSave.setEnabled(true);
        jbCancel.setEnabled(true);
    }

    private String CheckTextFeild() {
        String Error = "";
        boolean kt = true;
        if (jtxtUser.getText().equals("")) {
            Error += "UserName không được để trống\n";
        }
        if (jPass.getPassword() == null || jPass.getPassword().toString().length() < 8) {
            Error = Error + "Password không được để trống và Sử dụng ít nhất 8 ký tự. \n";
        }
        if (jtxtName.getText().equals("")) {
            Error = Error + "FullNam không được để trống \n";
        }
        String phone = jtxtPhone.getText();
        if(phone.equals(""))
        {}
        else
        {
        try {
            int a = Integer.parseInt(phone);
        } catch (NumberFormatException e) {
            kt = false;
        }
        if (kt == false) {
            Error = Error + "Số điện thoại phải nhập số\n ";
        }
        }
//        if (jtxtPhone.getText().equals("") || (kt == false)) {
//            Error = Error + "Phone không được để trông và phải nhập số\n ";
//        }
//        if (jTextField1.getText().equals("")) {
//            Error = Error + "Address không được để trống\n";
//        }
        return Error;
    }

    private void InsertButton() {
        String Error = CheckTextFeild();
        if (Error.equals("")) {
            if (UserManager.CheckUser(jtxtUser.getText()) == false) {
                User user = new User();
                user.setUSERNAME(jtxtUser.getText());
                user.setPASSWORD(new String(jPass.getPassword()));
                user.setENAME(jtxtName.getText());
                user.setPHONE((jtxtPhone.getText()));
                user.setADDRESS(jTextField1.getText());
                if (jadmin.isSelected()) {
                    user.setADMIN(true);
                } else {
                    user.setADMIN(false);
                }
                boolean temp = UserManager.InsertUser(user);
                if (temp) {
                    JOptionPane.showMessageDialog(this, "Thành Công");

                }

            } else {
                JOptionPane.showMessageDialog(this, "User đã tồn tại\n");
            }
        } else {
            JOptionPane.showMessageDialog(this, Error);
        }
    }

    private void EditButton() {
        String Error = CheckTextFeild();
        if (Error.equals("")) {
            if (UserManager.CheckUser(jtxtUser.getText()) == true) {
                User user = new User();
                user.setUSERNAME(jtxtUser.getText());
                user.setPASSWORD(new String(jPass.getPassword()));
                user.setENAME(jtxtName.getText());
                user.setPHONE((jtxtPhone.getText()));
                user.setADDRESS(jTextField1.getText());
                if (jadmin.isSelected()) {
                    user.setADMIN(true);
                } else {
                    user.setADMIN(false);
                }
                boolean temp = UserManager.UpdateUser(user);
                if (temp) {
                    JOptionPane.showMessageDialog(this, "Thành Công");
                }
            }
            else
            {
            JOptionPane.showMessageDialog(this, "User không tồn tại");
            }
        } else {
            JOptionPane.showMessageDialog(this, Error);
        }
    }

    private void reset() {
        dtbm.setRowCount(0);
    }
}
